package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author LiangTianQi
 * @describe
 * @date 2020/11/18 15:14
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    @PostMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map map) {
        //1、获取前端传来的电话号码，和验证码
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //2、从jedis中获取验证码
        Jedis jedis = jedisPool.getResource();
        String jedisCode = jedis.get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        jedis.close();
        if (validateCode == null || jedisCode == null || !validateCode.equals(jedisCode)) {
            return new Result(false,MessageConstant.VALIDATECODE_ERROR);
        }

        //向浏览器中添加cookie
        //向cookie中添加电话号码
        Cookie cookie = new Cookie("telephone",telephone);
        cookie.setPath("/");
        cookie.setMaxAge(60*60*24*30);
        response.addCookie(cookie);


        //3、调用service方法进行业务处理
        //3.1在业务中进行判断是否存在会员，不存在则创建一个
        //3.2想jedis中添加数据，当作全局session
        try {
            memberService.check(map);
            return new Result(true,MessageConstant.LOGIN_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true,"登陆失败");
        }

    }
}
